package com.ngc.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ngc.mall.bo.Spec;
import com.ngc.mall.common.configure.exception.BusinessException;
import com.ngc.mall.common.configure.mybatisPlus.BaseServiceImpl;
import com.ngc.mall.common.configure.response.ResponseCode;
import com.ngc.mall.domain.AttachmentDomain;
import com.ngc.mall.domain.SkuDomain;
import com.ngc.mall.domain.SkuSpecDomain;
import com.ngc.mall.domain.SpuDomain;
import com.ngc.mall.dto.*;
import com.ngc.mall.mapper.SpuMapper;
import com.ngc.mall.service.*;
import com.ngc.mall.vo.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SpuServiceImpl extends BaseServiceImpl<SpuMapper, SpuDomain> implements ISpuService {

    @Resource
    private ICosService iCosService;

    @Resource
    private IAttachmentService iAttachmentService;

    @Resource
    private ISkuService skuService;

    @Resource
    private ISkuSpecService skuSpecService;

    @Resource
    private IThemeService iThemeService;

    @Resource
    private ICategoryService iCategoryService;

    @Override
    public List<SpuDomain> selectAllSpu() {
       return super.list();
    }

    @Override
    public PagingVO<SpuDomain> search(SpuFilterDTO dto,int start,int count){
        Page<SpuDomain> page=new Page<>(start,count);
        LambdaQueryWrapper<SpuDomain> queryWrapper=Wrappers.<SpuDomain>lambdaQuery().orderByDesc(SpuDomain::getCreateTime);
        if(StringUtils.isNotBlank(dto.getTitle())){
            queryWrapper.like(SpuDomain::getTitle,dto.getTitle());
        }
        if(dto.getIsEnabled()!=null){
            queryWrapper.eq(SpuDomain::getOnline,dto.getIsEnabled());
        }
        if(StringUtils.isNotBlank(dto.getIds())){
            List<String> ids= Arrays.asList(dto.getIds().split(","));
            queryWrapper.in(SpuDomain::getCategoryId,ids);
        }
        if(dto.getCategoryId()!=null){
            queryWrapper.eq(SpuDomain::getCategoryId,dto.getCategoryId());
        }

        IPage iPage=super.page(page,queryWrapper);
        PagingVO<SpuDomain> pagingVO=new PagingVO<>(iPage);
        return pagingVO;
    }
    @Override
    @Transactional
    public Long createSpu(SpuDTO dto) {
        List<AttachmentDomain> carousels = new ArrayList<>();
//        List<AttachmentDomain> details=new ArrayList<>();
        SpuDomain domain=SpuDomain
                .builder()
                .title(dto.getTitle())
                .subTitle(dto.getSubTitle())
                .description(dto.getDescription())
                .online(dto.getOnline())
                .categoryId(dto.getCategoryId())
                .visualSpecId(dto.getVisualSpecId())
                .img(dto.getImg())
                .defaultSkuId(dto.getDefaultSkuId())
                .price(dto.getPrice())
                .sort(dto.getSort())
                .recommendStatus(dto.getRecommendStatus())
                .discountPrice(dto.getDiscountPrice())
                .detail(dto.getDetail())
                .build();
        Long spuId=super.create(domain);
        if(!dto.getThemeList().isEmpty()){
            iThemeService.insertBatchSpuTheme(spuId,dto.getThemeList());
        }
       if(!dto.getCarousels().isEmpty()){
           for(AttachmentDTO attachmentDTO:dto.getCarousels()){
               AttachmentDomain attachmentDomain=getAttachmentInfo(attachmentDTO,spuId);
               carousels.add(attachmentDomain);
           }
           Boolean batch=iAttachmentService.saveBatch(carousels);
           if(!batch){
               throw  new BusinessException(ResponseCode.ATTACHMENT_INSERT_FAIL);
           }
       }
//       if(!dto.getDetails().isEmpty()){
//           for(AttachmentDTO attachmentDTO:dto.getDetails()){
//               AttachmentDomain attachmentDomain=getAttachmentInfo(attachmentDTO,spuId);
//               details.add(attachmentDomain);
//           }
//       }
       if(!dto.getSkuList().isEmpty()){
           for(SkuDTO skuDTO:dto.getSkuList()){
               SkuDomain skuDomain=SkuDomain
                       .builder()
                       .spuId(spuId)
                       .stock(skuDTO.getStock())
                       .price(skuDTO.getPrice())
                       .title(dto.getTitle())
//                       .img(iCosService.getObjectUrl(skuDTO.getImg()))
                       .img(skuDTO.getImg())
                       .categoryId(dto.getCategoryId())
                       .build();
               Long skuId=skuService.createSku(skuDomain);
               List<SkuSpecDomain> skuSpecDomainList=new ArrayList<>();
               for(Spec spec:skuDTO.getSpecs()){
                   SkuSpecDomain skuSpecDomain=SkuSpecDomain
                           .builder()
                           .valueId(spec.getValueId())
                           .skuId(skuId)
                           .keyId(spec.getKeyId())
                           .spuId(spuId)
                           .value(spec.getValue())
                           .key(spec.getKey())
                           .build();
                   skuSpecDomainList.add(skuSpecDomain);
               }
               Boolean skuSpecBatch=skuSpecService.saveBatch(skuSpecDomainList);
               if (!skuSpecBatch){
                   System.out.println("插入失败");
               }
           }
       }


        return spuId;
    }


    public Boolean deleteSpuById(Long id){
        return true;
    }
    
    public AttachmentDomain getAttachmentInfo(AttachmentDTO attachmentDTO, Long id){
        FileInfoDTO fileInfoDTO=iCosService.getFormalObject(attachmentDTO.getFileName());
        AttachmentDomain attachmentDomain=AttachmentDomain
                .builder()
                .recordId(id)
                .sort(attachmentDTO.getSort())
                .fileSize(fileInfoDTO.getFileSize())
                .filePath(fileInfoDTO.getFileUrl())
                .type(attachmentDTO.getType())
                .fileType(getFileType(attachmentDTO.getFileName()))
                .build();
        return attachmentDomain;
    }

    public String getFileType(String fileName){
        String fileType=fileName.substring(fileName.lastIndexOf('.'));
        return fileType;
    }

    public Boolean updateSpuStatus(Boolean status,Long id){
        return super.update(Wrappers.<SpuDomain>lambdaUpdate().eq(SpuDomain::getId,id).set(SpuDomain::getOnline,status));
    }

    public Boolean updateSpuById(Long id,SpuDTO dto){
        SpuDomain domain=SpuDomain
                .builder()
                .title(dto.getTitle())
                .subTitle(dto.getSubTitle())
                .description(dto.getDescription())
                .online(dto.getOnline())
                .categoryId(dto.getCategoryId())
                .visualSpecId(dto.getVisualSpecId())
                .img(dto.getImg())
                .defaultSkuId(dto.getDefaultSkuId())
                .price(dto.getPrice())
                .sort(dto.getSort())
                .detail(dto.getDetail())
                .build();
        return super.update(domain,Wrappers.<SpuDomain>lambdaUpdate().eq(SpuDomain::getId,id));
//        if(dto.getThemeList()!=null){
////             Boolean result= iThemeService.deleteSpuById(id);
////             if(!result){
////                 System.out.println("删除失败");
////             }
////            System.out.println(id);
//             iThemeService.insertBatchSpuTheme(id,dto.getThemeList());
//        }
//        return true;

//        if (dto.getAttachmentDTOList()==null){
//            return true;
//        }
//        for(AttachmentDTO attachmentDTO:dto.getAttachmentDTOList()){
//            AttachmentDomain attachmentDomain=getAttachmentInfo(attachmentDTO,id);
//            attachmentDomainList.add(attachmentDomain);
//        }
//        Boolean batch=iAttachmentService.update(Wrappers.<AttachmentDomain>lambdaUpdate().eq(AttachmentDomain::getRecordId,id));
//        if(!batch){
//            throw new BusinessException(ResponseCode.ATTACHMENT_INSERT_FAIL);
//        }
//        return super.update(Wrappers.lambdaUpdate());

    }

    @Override
    public SpuVO getDetailById(Long id) {
        SpuDomain spuDomain=super.getById(id);
        System.out.println(spuDomain);
        List<AttachmentDomain> carouselDomainList=iAttachmentService
                .list(Wrappers.<AttachmentDomain>lambdaQuery()
                        .eq(AttachmentDomain::getRecordId,id)
                        .eq(AttachmentDomain::getType,1));
//        List<AttachmentDomain> detailDomainList=iAttachmentService
//                .list(Wrappers.<AttachmentDomain>lambdaQuery()
//                .eq(AttachmentDomain::getRecordId,id)
//                .eq(AttachmentDomain::getType,2));
        List<AttachmentVO> carousels = new ArrayList<>();
//        List<AttachmentVO> details=new ArrayList<>();
        ///轮播图
        for (AttachmentDomain attachmentDomain:carouselDomainList){
            AttachmentVO attachmentVO=AttachmentVO
                    .builder()
                    .fileName(attachmentDomain.getFilePath())
                    .sort(attachmentDomain.getSort())
                    .id(attachmentDomain.getId())
                    .build();
            carousels.add(attachmentVO);
        }
//        ///详情图
//        for (AttachmentDomain attachmentDomain:detailDomainList){
//            AttachmentVO attachmentVO=AttachmentVO
//                    .builder()
//                    .fileName(attachmentDomain.getFilePath())
//                    .sort(attachmentDomain.getSort())
//                    .id(attachmentDomain.getId())
//                    .build();
//            details.add(attachmentVO);
//        }
        List<SkuDTO> skuDTOList=skuService.findBySpuId(id).stream().map(c->SkuDTO.builder().id(c.getId()).img(c.getImg()).price(c.getPrice()).specs(c.getSpecs()).spuId(c.getSpuId()).stock(c.getStock()).title(c.getTitle()).build()
        ).collect(Collectors.toList());
        SpuVO vo=SpuVO.builder()
                .sort(spuDomain.getSort())
                .img(spuDomain.getImg())
                .categoryId(spuDomain.getCategoryId())
                .id(spuDomain.getId())
                .subTitle(spuDomain.getSubTitle())
                .defaultSkuId(spuDomain.getDefaultSkuId())
                .online(spuDomain.getOnline())
                .price(spuDomain.getPrice())
                .description(spuDomain.getDescription())
                .carousels(carousels)
                .detail(spuDomain.getDetail())
                .recommendStatus(spuDomain.getRecommendStatus())
                .discountPrice(spuDomain.getDiscountPrice())
                .skuList(skuDTOList)
                .visualSpecId(spuDomain.getVisualSpecId())
                .title(spuDomain.getTitle())
                .themeList(iThemeService.findIdBySpus(id))
                .build();
        return vo;
    }

    @Override
    public SpuSimplifyVO getSimplifyById(Long id) {
        SpuDomain domain=super.getById(id);
        return SpuSimplifyVO.builder().img(domain.getImg()).title(domain.getTitle()).subTitle(domain.getSubTitle()).build();
    }

    @Override
    public PagingVO<SpuDomain> getSpuListByCategoryId(List<Long> categoryIdList,int current,int size) {
        Page<SpuDomain> page=new Page<>(current,size);
        ///所有子分类id下的spuList的合并
        IPage<SpuDomain> iPage=super.page(page,Wrappers.<SpuDomain>lambdaQuery().in(SpuDomain::getCategoryId,categoryIdList));
        PagingVO<SpuDomain> pagingVO=new PagingVO<>(iPage);
        return pagingVO;
    }


    @Override
    public SpuOverviewVO getSpuOverview() {
        int minStock=10;
        Integer onlineSpuCount=super.count(Wrappers.<SpuDomain>lambdaQuery().eq(SpuDomain::getOnline,true));
        Integer offlineSpuCount=super.count(Wrappers.<SpuDomain>lambdaQuery().eq(SpuDomain::getOnline,false));
        Integer outOffStockCount=skuService.count(Wrappers.<SkuDomain>lambdaQuery().lt(SkuDomain::getStock,minStock));
        Integer totalSpuCount=super.count();
        return SpuOverviewVO
                .builder()
                .totalSpuCount(totalSpuCount)
                .onlineSpuCount(onlineSpuCount)
                .offlineSpuCount(offlineSpuCount)
                .outOffStockCount(outOffStockCount)
                .build();
    }

    @Override
    public PagingVO<SpuDomain> findByTitleLikeAndSubTitleLike(String q, int start, int count) {
        Page<SpuDomain> page=new Page<>(start,count);
        IPage iPage=super.page(page,Wrappers.<SpuDomain>lambdaQuery().like(SpuDomain::getTitle,q));
        PagingVO<SpuDomain> pagingVO=new PagingVO<>(iPage);
        return pagingVO;
    }

    @Override
    public PagingVO<SpuDomain> getPageList(int start, int count){
        Page<SpuDomain> page=new Page<>(start,count);
        IPage iPage= super.page(page,Wrappers.<SpuDomain>lambdaQuery().eq(SpuDomain::getOnline,true));
        PagingVO<SpuDomain> pagingVO= new PagingVO(iPage);
        return pagingVO;
    }

}
